package com.etoc.test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.sql.DataSource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class GenDataProcess {
	public static Map<String, List<String>> cachedMap = new HashMap<>(180);
	public static Map<String, String> areaMap;
	public static Map<String, String> mobileOperMap;
	public static DataSource ds;
	private static Log log = LogFactory.getLog(GenDataProcess.class);
	
	static {
		ds = getDataSource("jdbc:mysql://127.0.0.1:3306/channel_core", "root", "root", "com.mysql.jdbc.Driver", 20, 100, 90, 300000, 10);
		areaMap = new HashMap<>(45);
		areaMap.put("全国", "000000");
		areaMap.put("北京", "110000");
		areaMap.put("天津", "120000");
		areaMap.put("河北", "130000");
		areaMap.put("山西", "140000");
		areaMap.put("内蒙", "150000");
		areaMap.put("辽宁", "210000");
		areaMap.put("吉林", "220000");
		areaMap.put("黑龙", "230000");
		areaMap.put("上海", "310000");
		areaMap.put("江苏", "320000");
		areaMap.put("浙江", "330000");
		areaMap.put("安徽", "340000");
		areaMap.put("福建", "350000");
		areaMap.put("江西", "360000");
		areaMap.put("山东", "370000");
		areaMap.put("河南", "410000");
		areaMap.put("湖北", "420000");
		areaMap.put("湖南", "430000");
		areaMap.put("广东", "440000");
		areaMap.put("广西", "450000");
		areaMap.put("海南", "460000");
		areaMap.put("重庆", "500000");
		areaMap.put("四川", "510000");
		areaMap.put("贵州", "520000");
		areaMap.put("云南", "530000");
		areaMap.put("西藏", "540000");
		areaMap.put("陕西", "610000");
		areaMap.put("甘肃", "620000");
		areaMap.put("青海", "630000");
		areaMap.put("宁夏", "640000");
		areaMap.put("新疆", "650000");
		areaMap.put("台湾", "710000");
		areaMap.put("香港", "810000");
		areaMap.put("澳门", "820000");
		mobileOperMap = new HashMap<>(3);
		mobileOperMap.put("联通", "CU");
		mobileOperMap.put("移动", "CM");
		mobileOperMap.put("电信", "CN");
		mobileOperMap.put("CU", "CU");
		mobileOperMap.put("CM", "CM");
		mobileOperMap.put("CN", "CN");
	}
	
	public static void main(String[] args) throws Exception {
		// 读取源文件，格式：月份、客户名称、产品名称、成功数量、成功金额、产品折后价、产品原价、产品折扣
		List<String> lineDatas = IOUtils.readLines(new FileInputStream("d:/dat.txt"));
		File destFile = new File("d:/shangtong_201701_plus.txt");
		if (destFile.exists()) {
			destFile.delete();
		}
		BufferedWriter bw = new BufferedWriter(new FileWriter(destFile, true), 2048);
		for (String lineData : lineDatas) {
			String[] colDatas = lineData.split("\t");
			String col1 = colDatas[0];// 月份
			String col2 = colDatas[1];// 供应商名称
			String col3 = colDatas[2];// 产品名称
			String col4 = colDatas[6];// 产品单价
			String col5 = colDatas[3];// 成功数量
			String col6 = colDatas[7];// 上游折扣
			//String col7 = colDatas[4];// 成本
			Date startDate = DateUtils.parseDate(col1, "yyyyMM");
			Date endDate = DateUtils.addMonths(startDate, 1);
			BigDecimal productPrice = new BigDecimal(col4);
			Integer saleSucs =  new Integer(col5);
			BigDecimal saleDiscount = new BigDecimal(col6);
			//BigDecimal saleMoney =  new BigDecimal(col7);
			
			// 需要生成详单数
			List<String> newLineDatas = new ArrayList<>(saleSucs);
			for (int i = 0; i < saleSucs; i++) {
				Long timestamp= RandomUtils.nextLong(startDate.getTime(), endDate.getTime());
				Date orderTime = new Date(timestamp);// 订购时间:out
				String date = DateFormatUtils.format(orderTime, "yyyyMMdd");// 结算期:out
				String mobileOper = parseMobileOper(col3);
				String areaId = parseAreaId(col3);
				String phoneNo = genPhoneNo(mobileOper, areaId);// 手机号码:out
				String orderId = genOrderId(orderTime);// 订单号:out
				String orderResult = "成功";// 描述:out
				String productName = col3;// 产品名称:out
				BigDecimal salePrice = productPrice.multiply(saleDiscount);// 折扣单价:out
				String transNo = genOrderId(orderTime);// 上游订单号:out
				
				StringBuffer sb = new StringBuffer(DateFormatUtils.format(orderTime, "yyyy-MM-dd HH:mm:dd")).append("\t")
						.append(col2).append("\t")
						.append(orderId).append("\t")
						.append(phoneNo).append("\t")
						.append(productPrice.setScale(4)).append("\t")
						.append(saleDiscount.setScale(4)).append("\t")
						.append(salePrice.setScale(4)).append("\t")
						.append(date).append("\t")
						.append(orderResult).append("\t")
						.append(productName).append("\t")
						.append(transNo);
				newLineDatas.add(sb.toString());
				log.info("for end: " + sb.toString());
			}
			IOUtils.writeLines(newLineDatas, "\r\n", bw);
			log.info("write " + newLineDatas.size() + " records");
		}
		IOUtils.closeQuietly(bw);
	}

	private static String genOrderId(Date orderTime) {
		String orderId = DateFormatUtils.format(orderTime, "yyMMddHHmmss" + RandomUtils.nextInt(1, 7) + RandomStringUtils.random(2, "000001") + RandomStringUtils.random(1, "111123"));
		return orderId;
	}

	private static String genPhoneNo(String mobileOper, String areaId) throws Exception {
		List<String> phoneNos = cachedMap.get(mobileOper + "-" + areaId);
		if (CollectionUtils.isEmpty(phoneNos)) {
			Connection conn = ds.getConnection();
			QueryRunner qRunner = new QueryRunner();
			String sql = null;
			if (areaId.equals("000000")) {
				sql = "select left(a.begin_no, 7) phone_no from area_phone_info a where a.mobile_operator=? ";
				phoneNos = (List<String>)qRunner.query(conn, sql, new ColumnListHandler<String>(), mobileOper);
			} else {
				sql = "select left(a.begin_no, 7) phone_no from area_phone_info a where a.mobile_operator=? and concat(left(a.area_id, 2), '0000')=? ";
				phoneNos = (List<String>)qRunner.query(conn, sql, new ColumnListHandler<String>(), mobileOper, areaId);
			}
			cachedMap.put(mobileOper + "-" + areaId, phoneNos);
			DbUtils.closeQuietly(conn);
		}
		// 随机取一个
		int randIndex = org.apache.commons.lang.math.RandomUtils.nextInt(phoneNos.size());
		return phoneNos.get(randIndex) + "****";
	}
	
	private static String parseAreaId(String col3) {
		String areaId = null;
		Set<String> areaNames = areaMap.keySet();
		for (String areaName : areaNames) {
			if (col3.contains(areaName)) {
				areaId = areaMap.get(areaName);
				break;
			}
		}
		return areaId;
	}

	private static String parseMobileOper(String col3) {
		String mobileOper = null;
		Set<String> mobileOperNames = mobileOperMap.keySet();
		for (String mobileOperName : mobileOperNames) {
			if (col3.contains(mobileOperName)) {
				mobileOper = mobileOperMap.get(mobileOperName);
				break;
			}
		}
		return mobileOper;
	}
	
	private static DataSource getDataSource(String connectURI, String username, String pswd,  
            String driverClass, int initialSize, int maxtotal, int maxIdle,  
            int minIdle, int maxWaitMillis) {
		BasicDataSource ds = new BasicDataSource();
		ds.setDriverClassName(driverClass);  
        ds.setUsername(username);  
        ds.setPassword(pswd);  
        ds.setUrl(connectURI);  
        ds.setInitialSize(initialSize);
        ds.setMaxTotal(maxtotal);
        ds.setMaxIdle(maxIdle);  
        ds.setMinIdle(minIdle);  
        ds.setMaxWaitMillis(maxWaitMillis);  
        return ds;
	}
}


